<?php
namespace Admin\Controller;
use Think\Controller;
class UserController extends BaseController{
	public function userlist(){	// 用户列表
		$User = D('User');
		$userlist = $User->select();
		$this->assign('userlist', $userlist);
		$this->display();
	}

	public function adduser(){	// 新增用户
		$Role = D('Role');
		$rolelist = $Role->select();
		$this->assign('rolelist', $rolelist);
		$this->display();
	}

	public function adduserHandle(){	// 新增用户处理
		$username = I('post.username');
		$name = I('post.name');
		$password = I('post.password');
		$rid = I('post.rid', 0);
		$User = D('User');
		$res = $User->addUser($username, $password, $name, $rid);
		if($res === false){
			$this->error('用户名已存在或用户名密码规则有误', U('Admin/User/adduser'));
		}else{
			$this->redirect('Admin/User/adduser', array(), 0);
		}
	}

	public function updateuser($user_id=null){		//更新用户，根据有无user_id判断跳转列表页还是修改页
		$user=D('User');
		if($user_id==null){
			$userlist=$user->select();
			$this->assign("userlist",$userlist);
			$this->display("User/updatelist");
		}
		else{
			$userinfo=$user->where(array("id"=>$user_id))->find();
			if($userinfo==false){
				$this->error("用户名不存在!",U("Admin/User/updateuser"));
			}else{
				$role=D("Role");
				$rolelist=$role->select();
				$this->assign("user",$userinfo);
				$this->assign("rolelist",$rolelist);
				$this->assign("uid",$user_id);
				$this->display();
			}

		}
	}

	public function updateuserhandle(){			//更新用户处理，不单纯依靠数据库来判断数据真实性
		$uid=I("post.uid");
		$username=I("post.username");
		$name=I("post.name");
		$password=I("post.password");
		$rid=I("post.rid");
		$where['id']=$uid;
		$user=D("User");
		$res=$user->where($where)->find();
		if($res===false){
			$this->error("用户名不存在！",U("Admin/User/updateuser"));
		}
		else{
			$data['id']=$uid;
			$data['username']=$username;
			$data['name']=$name;
			$data['role_id']=$rid;
			$res=$user->save($data);
			if ($res===false) {
				$this->error("修改失败，请重试或联系管理员!",U("Admin/User/updateuser"));
			}
			else{
				$this->success("修改成功!",U("Admin/User/updateuser"));
			}
		}
	}

	public function deleteuser($user_id=null){		//删除用户处理
		if($user_id==null){
			$this->error('用户信息为空，请重试!',U('Admin/User/updateuser'));
		}
		else{
			$user=D("User");
			$where['id']=$user_id;
			$res=$user->where($where)->delete();
			if($res===false){
				$this->error('删除失败，请重试！',U('Admin/User/updateuser'));
			}
			else{
				$this->success('删除成功！',U('Admin/User/updateuser'));
			}
		}

	}

	public function resetPassword(){
		$uid = I("post.uid");
		$User = D('User');
		$newpassword = C('RESET_PASSWD');
		if($User->resetPassword($uid, $newpassword) !== false){
			$this->ajaxReturn(array('opstatus'=>'success','uid'=>$uid, 'new'=>$newpassword));
		}
		$this->ajaxReturn(array('opstatus'=>'error','uid'=>$uid, 'new'=>$newpassword));
	}
}
